<template>
  <div class="telemedicine-container">
    <!-- 头部导航 -->
    <div class="header">
      <h1 style="color: #1a73e8;">您好！我是你的医疗管家</h1>
      <div class="model-info">
        <span>当前模型: {{ currentModel.name }}</span>
        <el-tooltip effect="dark" :content="currentModel.description" placement="bottom">
          <el-icon><InfoFilled /></el-icon>
        </el-tooltip>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="main-content">
      <!-- 左侧问诊面板 -->
      <div class="consultation-panel">
        <!-- 模型选择 -->
        <div class="model-selector">
          <el-radio-group v-model="selectedModel" @change="switchModel">
            <el-radio-button label="western">西医诊断</el-radio-button>
            <el-radio-button label="tcm">中医问诊</el-radio-button>
          </el-radio-group>
        </div>

        <!-- 聊天区域 -->
        <div class="chat-container">
          <div class="messages" ref="messagesRef">
            <div v-for="(message, index) in messages" :key="index" class="message" :class="message.role">
              <div class="role-name">{{ roleNames[message.role] }}</div>
              <div class="text">
                <template v-if="message.role === 'assistant' && message.loading">
                  <el-icon class="loading-icon"><Loading /></el-icon>
                  思考中...
                </template>
                <template v-else>
                  <div v-html="formatMessage(message.content)"></div>
                </template>
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="input-area">
            <el-input
                v-model="userInput"
                type="textarea"
                :rows="3"
                placeholder="请描述您的症状..."
                @keyup.enter="sendMessage"
            ></el-input>
            <div class="actions">
              <el-button @click="clearConversation">清空对话</el-button>
              <el-button type="primary" @click="sendMessage" :loading="isLoading">发送</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧诊断面板 -->
      <div class="diagnosis-panel">
        <div class="panel-header">
          <h3>诊断结果</h3>
          <el-button type="text" @click="generateReport" :loading="isGeneratingReport">
            生成报告
          </el-button>
        </div>

        <div v-if="diagnosisResult">
          <div class="diagnosis-section">
            <h4>初步诊断</h4>
            <p>{{ diagnosisResult.preliminaryDiagnosis }}</p>
          </div>

          <div class="diagnosis-section" v-if="selectedModel === 'western'">
            <h4>建议检查</h4>
            <ul>
              <li v-for="(test, index) in diagnosisResult.suggestedTests" :key="index">{{ test }}</li>
            </ul>
          </div>

          <div class="diagnosis-section" v-if="selectedModel === 'tcm'">
            <h4>中医辨证</h4>
            <p>{{ diagnosisResult.tcmSyndrome }}</p>
          </div>

          <div class="diagnosis-section">
            <h4>治疗建议</h4>
            <ul>
              <li v-for="(advice, index) in diagnosisResult.treatmentAdvice" :key="index">{{ advice }}</li>
            </ul>
          </div>

          <div class="diagnosis-section" v-if="diagnosisResult.medications && diagnosisResult.medications.length > 0">
            <h4>药物建议</h4>
            <ul>
              <li v-for="(med, index) in diagnosisResult.medications" :key="index">
                {{ med.name }} - {{ med.dosage }} ({{ med.frequency }})
              </li>
            </ul>
          </div>

          <div class="diagnosis-section" v-if="diagnosisResult.notes">
            <h4>注意事项</h4>
            <p>{{ diagnosisResult.notes }}</p>
          </div>
        </div>

        <div v-else class="empty-diagnosis">
          <el-empty description="暂无诊断结果" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled, Loading } from '@element-plus/icons-vue'

export default {
  name: 'Telemedicine',
  components: {
    InfoFilled,
    Loading
  },
  setup() {
    // 模型配置
    const models = {
      western: {
        name: '西医诊断模型',
        description: '基于最新医学指南的西医诊断AI，提供精准的现代医学诊断建议',
        endpoint: 'https://api.medical-ai.com/western/v1/chat',
        apiKey: 'YOUR_WESTERN_API_KEY'
      },
      tcm: {
        name: '中医问诊模型',
        description: '融合传统中医理论和现代AI技术的中医辨证系统',
        endpoint: 'https://api.medical-ai.com/tcm/v1/chat',
        apiKey: 'YOUR_TCM_API_KEY'
      }
    }

    // 响应式数据
    const selectedModel = ref('western')
    const currentModel = computed(() => models[selectedModel.value])
    const userInput = ref('')
    const messages = ref([])
    const messagesRef = ref(null)
    const isLoading = ref(false)
    const isGeneratingReport = ref(false)
    const diagnosisResult = ref(null)

    // 角色名称映射
    const roleNames = {
      user: '患者',
      assistant: 'AI医生'
    }

    // 初始化欢迎消息
    const initWelcomeMessage = () => {
      messages.value = [
        {
          role: 'assistant',
          content: selectedModel.value === 'western'
              ? '您好，我是AI西医医生。请描述您的症状、持续时间以及任何相关病史，我将为您提供专业的诊断建议。'
              : '您好，我是AI中医师。请描述您的症状、持续时间以及舌象、脉象等信息，我将为您辨证施治。',
          loading: false
        }
      ]
    }

    // 切换模型
    const switchModel = () => {
      clearConversation()
      initWelcomeMessage()
    }

    // 清空对话
    const clearConversation = () => {
      messages.value = []
      diagnosisResult.value = null
      initWelcomeMessage()
    }

    // 格式化消息内容
    const formatMessage = (content) => {
      // 简单的换行处理
      return content.replace(/\n/g, '<br>')
    }

    // 发送消息
    const sendMessage = async () => {
      if (!userInput.value.trim()) {
        ElMessage.warning('请输入您的问题')
        return
      }

      if (isLoading.value) return

      // 添加用户消息
      messages.value.push({
        role: 'user',
        content: userInput.value,
        loading: false
      })

      // 添加AI思考中的消息
      messages.value.push({
        role: 'assistant',
        content: '',
        loading: true
      })

      const userMessage = userInput.value
      userInput.value = ''
      isLoading.value = true

      try {
        // 滚动到底部
        await nextTick()
        scrollToBottom()

        // 模拟API调用 - 实际项目中替换为真实的API调用
        const response = await mockApiCall(userMessage, selectedModel.value)

        // 移除loading消息，添加真实响应
        messages.value.pop()
        messages.value.push({
          role: 'assistant',
          content: response.message,
          loading: false
        })

        // 更新诊断结果
        if (response.diagnosis) {
          diagnosisResult.value = response.diagnosis
        }
      } catch (error) {
        console.error('API调用失败:', error)
        messages.value.pop()
        messages.value.push({
          role: 'assistant',
          content: '抱歉，处理您的请求时出现问题。请稍后再试。',
          loading: false
        })
        ElMessage.error('请求失败，请稍后再试')
      } finally {
        isLoading.value = false
        await nextTick()
        scrollToBottom()
      }
    }

    // 生成报告
    const generateReport = async () => {
      if (!messages.value.length || messages.value.length < 2) {
        ElMessage.warning('对话内容不足，无法生成报告')
        return
      }

      isGeneratingReport.value = true

      try {
        // 模拟生成报告 - 实际项目中替换为真实的API调用
        await new Promise(resolve => setTimeout(resolve, 1500))
        ElMessage.success('报告生成成功')

        // 这里可以添加实际下载报告的逻辑
      } catch (error) {
        console.error('生成报告失败:', error)
        ElMessage.error('生成报告失败')
      } finally {
        isGeneratingReport.value = false
      }
    }

    // 滚动到底部
    const scrollToBottom = () => {
      if (messagesRef.value) {
        messagesRef.value.scrollTop = messagesRef.value.scrollHeight
      }
    }

    // 模拟API调用
    const mockApiCall = async (message, modelType) => {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 1500))

      // 根据模型类型返回不同的响应
      if (modelType === 'western') {
        return {
          message: `根据您描述的症状，初步考虑可能是上呼吸道感染。建议：
1. 多休息，多饮水
2. 可考虑服用解热镇痛药如对乙酰氨基酚缓解症状
3. 如症状持续超过3天或加重，建议就医检查`,
          diagnosis: {
            preliminaryDiagnosis: '上呼吸道感染（普通感冒）',
            suggestedTests: ['血常规', 'C反应蛋白检测', '胸部X光（如症状严重）'],
            treatmentAdvice: [
              '多休息，保证充足睡眠',
              '多饮水，保持水分',
              '可服用解热镇痛药缓解症状',
              '如出现高热不退或呼吸困难及时就医'
            ],
            medications: [
              {
                name: '对乙酰氨基酚',
                dosage: '500mg',
                frequency: '每6小时一次，每日不超过4次'
              }
            ],
            notes: '注意观察症状变化，如出现持续高热、呼吸困难或其他严重症状，请立即就医。'
          }
        }
      } else {
        return {
          message: `根据您的症状描述，辨证为风热感冒。建议：
1. 服用银翘散加减
2. 多饮温水，避免辛辣食物
3. 可配合穴位按摩如合谷、风池穴`,
          diagnosis: {
            preliminaryDiagnosis: '感冒（风热证）',
            tcmSyndrome: '风热犯表证，症见发热重、恶风、头胀痛、有汗、咽喉红肿疼痛、咳嗽、痰粘或黄、鼻塞流黄涕、口渴喜饮',
            treatmentAdvice: [
              '辛凉解表，清热解毒',
              '饮食宜清淡，忌辛辣油腻',
              '可配合刮痧或拔罐疗法',
              '保持室内空气流通'
            ],
            medications: [
              {
                name: '银翘散',
                dosage: '9g',
                frequency: '每日2次，温水冲服'
              },
              {
                name: '板蓝根冲剂',
                dosage: '1包',
                frequency: '每日3次'
              }
            ],
            notes: '注意避风保暖，观察体温变化。如高热不退或症状加重，请及时就医。'
          }
        }
      }
    }

    // 初始化欢迎消息
    initWelcomeMessage()

    // 监听消息变化，自动滚动
    watch(messages, () => {
      nextTick(() => {
        scrollToBottom()
      })
    }, { deep: true })

    return {
      selectedModel,
      currentModel,
      userInput,
      messages,
      messagesRef,
      isLoading,
      isGeneratingReport,
      diagnosisResult,
      roleNames,
      switchModel,
      clearConversation,
      formatMessage,
      sendMessage,
      generateReport
    }
  }
}
</script>

<style scoped>
.telemedicine-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.header {
  padding: 20px;
  background-color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.model-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.consultation-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: white;
  margin: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.model-selector {
  margin-bottom: 20px;
}

.chat-container {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  margin-bottom: 20px;
}

.message {
  margin-bottom: 16px;
}

.message.user {
  text-align: right;
}

.role-name {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.message.user .role-name {
  text-align: right;
}

.text {
  padding: 12px;
  border-radius: 8px;
  line-height: 1.5;
  display: inline-block;
  max-width: 80%;
  word-wrap: break-word;
}

.message.user .text {
  background-color: #409eff;
  color: white;
}

.message.assistant .text {
  background-color: #f2f6fc;
  color: #303133;
}

.loading-icon {
  animation: rotating 2s linear infinite;
  margin-right: 8px;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.input-area {
  margin-top: 20px;
}

.actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.diagnosis-panel {
  width: 400px;
  padding: 20px;
  background-color: white;
  overflow-y: auto;
  margin: 20px 20px 20px 0;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.diagnosis-section {
  margin-bottom: 20px;
}

.diagnosis-section h4 {
  margin: 0 0 10px 0;
  color: #409eff;
}

.diagnosis-section p, .diagnosis-section ul {
  margin: 0;
  color: #606266;
}

.diagnosis-section ul {
  padding-left: 20px;
}

.empty-diagnosis {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
